package com.esdk.sql.orm;

import cn.hutool.core.net.NetUtil;
import com.esdk.esdk;

import java.net.InetAddress;
import java.util.Date;

/**
 * @author ffychina@163.com
 * @since 2024-04-24
 * 实现了一个类雪花算法，输出长度是15位数字，输出到前端不会和丢失精度。
 * */

public class IntegerFlake{
  private static int MaxIndex=100;
  private static InetAddress localhost =NetUtil.getLocalhost();
  private static int sequence = 0; // 序列号
  private static long lastStmp = -1;// 上一次时间戳
  private static final int machineId=getMachineId()*10000;
  private static final long salt=13*100000000L;
  synchronized static public long nextId(){
    long timestamp =System.currentTimeMillis()/1000+salt;
    sequence=lastStmp!=timestamp?0:sequence+1;
    lastStmp=timestamp;
    long result=timestamp*100000+machineId+sequence;
    return result;
  }

  public static Date toDate(long nextId){
    return new Date((nextId/100000-salt)*1000);
  }

  private static int getMachineId(){
    int machineId=0;
    byte[] address=localhost.getAddress();
    int hashCode = 0;
    for (byte b : address) {
      hashCode += b & 0xFF;
    }
    machineId=Math.abs(hashCode) % MaxIndex;
    return machineId;
  }

  public static void main(String[] args){
    for(int i=0;i<200;i++){
      long nextId=nextId();
      esdk.sout("{} nextId:{}",System.currentTimeMillis(),nextId);
    }
  }
}
